package com.xxx.config.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxx.pojo.RespBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当未登录或者token失效时访问接口，自定义的返回结果
 * @author WXH
 * @version 1.0
 * @date 2022/2/23 20:48
 */
@Component
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");//设置编码格式为UTF-8
        response.setContentType("application/json"); //设置数据格式为json格式
        PrintWriter out = response.getWriter();   //拿到输出流
        RespBean bean = RespBean.error("未登录，请登录");     //未登录或失效
        bean.setCode(401);
        out.write(new ObjectMapper().writeValueAsString(bean));//输出数据
        out.flush();
        out.close();
    }
}
